package com.sense.ioc.bean;

import com.sense.ioc.annotation.Reference;
import com.sense.ioc.register.IocRegister;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Creator: LanJian (lanjian860217@gmail.com)
 * Date: 1/31/11
 * Time: 4:12 PM
 */
public class BeanDefinition {
    private String beanName;
    private boolean singleton;
    private Class clazz;
    private boolean lazy = true;
    private String initMethod;
    private ThreadLocal<Object> threadLocal = new ThreadLocal<Object>();

    public BeanDefinition(String beanName, Class clazz, boolean singleton, String initMethod) {
        this.beanName = beanName;
        this.clazz = clazz;
        this.singleton = singleton;
        this.initMethod = initMethod;
    }

    public boolean isOK() {
        return true;
    }

    public boolean isLazy() {
        return lazy;
    }

    public void setLazy(boolean lazy) {
        this.lazy = lazy;
    }

    public Object newInstance() throws InstantiationException, IllegalAccessException {
        Object object = null;
        if (singleton) {
            if (threadLocal.get() == null) {
                threadLocal.set(clazz.newInstance());
            }
            object = threadLocal.get();
        } else {
            object = clazz.newInstance();
        }
        return object;
    }

    public void fixReferences() throws IllegalAccessException, InstantiationException {
        if (clazz != null) {
            Field[] fields = clazz.getFields();
            if (singleton) {
                for (Field field : fields) {
                    if (field.isAnnotationPresent(Reference.class)) {
                        Reference reference = field.getAnnotation(Reference.class);
                        Class referenceClass = reference.refClass();
                        field.set(newInstance(), IocRegister.findBean(referenceClass));
                    }
                }
            } else {

            }

        } else {
            throw new RuntimeException("bean definition error," + beanName + " class is null!");
        }
    }

    public String getBeanName() {
        return beanName;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public boolean isSingleton() {
        return singleton;
    }

    public void setSingleton(boolean singleton) {
        this.singleton = singleton;
    }

    public Class getClazz() {
        return clazz;
    }

    public void setClazz(Class clazz) {
        this.clazz = clazz;
    }

    public String getInitMethod() {
        return initMethod;
    }

    public void setInitMethod(String initMethod) {
        this.initMethod = initMethod;
    }
}
